package com.yami.shop.api.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.app.dto.OrderCountData;
import com.yami.shop.bean.app.dto.UserCenterInfoDto;
import com.yami.shop.bean.app.dto.UserDto;
import com.yami.shop.bean.app.dto.UserInfoDto;
import com.yami.shop.bean.app.param.*;
import com.yami.shop.bean.enums.SendType;
import com.yami.shop.bean.event.UpdateDistributionUserEvent;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.param.UserParam;
import com.yami.shop.bean.vo.UserBalanceWithdrawCashConfigVO;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.constants.UserCacheNames;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.handler.SensitiveHandler;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.i18n.LanguageEnum;
import com.yami.shop.common.response.ResponseEnum;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.BeanUtil;
import com.yami.shop.common.util.IPHelper;
import com.yami.shop.common.util.PrincipalUtil;
import com.yami.shop.common.util.RedisUtil;
import com.yami.shop.distribution.common.dto.AchievementDataDto;
import com.yami.shop.distribution.common.dto.DistributionUserWalletDto;
import com.yami.shop.distribution.common.model.DistributionUser;
import com.yami.shop.distribution.common.service.DistributionUserService;
import com.yami.shop.rights.common.service.RightsVerificationUserService;
import com.yami.shop.security.api.model.YamiUser;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.security.common.manager.PasswordManager;
import com.yami.shop.service.*;
import com.yami.shop.user.common.dto.UserBalanceWithdrawCashSetDto;
import com.yami.shop.user.common.service.UserBalanceWithdrawCashService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用户信息
 *
 * @author LGH
 */
@RestController
@RequestMapping("/p/user")
@Tag(name = "用户接口")
@AllArgsConstructor
public class UserController {

    private final UserService userService;

    private final ApplicationContext applicationContext;

    private final OrderService orderService;

    private final ShopDetailService shopDetailService;

    private final ShopAuditingService shopAuditingService;

    private final SmsLogService smsLogService;

    private final PasswordEncoder passwordEncoder;

    private final PasswordManager passwordManager;

    private final UserExtensionService userExtensionService;

    private DistributionUserService distributionUserService;

    private final MeltCloudUserService meltCloudUserService;

    private final RightsVerificationUserService rightsVerificationUserService;

    private final UserBalanceWithdrawCashService userBalanceWithdrawCashService;

    private final SensitiveHandler sensitiveHandler;
    public static final String CHECK_SET_PAY_PWD_SMS_FLAG = "setPayPwdSmsFlag";
    public final SysConfigService sysConfigService;

    @GetMapping("/userInfo")
    @Operation(summary = "查看用户信息", description = "根据用户ID（userId）获取用户信息")
    public ServerResponseEntity<UserDto> userInfo() {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getUserByUserId(userId);
        if (Objects.isNull(user)) {
            return ServerResponseEntity.success();
        }

        // 判断用户是否已有二维码，没有则生成
        if (StringUtils.isBlank(user.getQrcodeAddr())) {
            String qrcodeAddr = userService.createUserQrcode(true, userId, user.getPic());
            user.setQrcodeAddr(qrcodeAddr);
        }

        // 获取用户等级积分详细表
        UserExtension extension = userExtensionService.getOne(
                new LambdaQueryWrapper<UserExtension>().eq(UserExtension::getUserId, SecurityUtils.getUser().getUserId()));
        UserDto userDto = BeanUtil.map(user, UserDto.class);
        if(Objects.nonNull(extension)){
            userDto.setLevel(extension.getLevel());
            userDto.setGrowth(extension.getGrowth());
            userDto.setScore(extension.getScore());
            userDto.setLevelType(extension.getLevelType());
            userDto.setBalance(extension.getBalance());
        }

        userDto.setUsername(user.getUserName());
        userDto.setProdRecommendation(user.getProdRecommendation());
        userDto.setIsSetPayPwd(StrUtil.isNotBlank(user.getPayPassword()));
        if (userDto.getUserMobile() != null) {
            userDto.setMobile(userDto.getUserMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
        }
        if (StringUtils.isNotEmpty(userDto.getRealName())) {
            String s = StringUtils.right(userDto.getRealName(), 1);
            String name = StringUtils.leftPad(s, StringUtils.length(userDto.getRealName()), "*");
            userDto.setRealName(name);
        }
        if (StringUtils.isNotEmpty(userDto.getIdNumber())) {
            userDto.setIdNumber(userDto.getIdNumber().replaceAll("(\\d{1})\\d{16}(\\d{1})", "$1****************$2"));
        }
        userDto.setProvince(IPHelper.getIpProvinceAddr(user.getUserRegip()));
        // 获取融云用户Id
        MeltCloudUser meltCloudUser = meltCloudUserService.getById(userId);
        if (ObjectUtils.isNotEmpty(meltCloudUser)) {
            userDto.setMeltUserToken(meltCloudUser.getUserToken());
        }
        // 查询该用户是否有核销权限
        boolean isVerificationRights = rightsVerificationUserService.isVerificationRightsByUserId(user.getUserId());
        userDto.setIsVerificationRights(isVerificationRights);
        //查询用户是否成年玩转nft //无实名当成年
        Boolean bigMan = false;
        try {
            bigMan = userService.isBigMan(user.getIdNumber());
        }catch (Exception e){}
        Boolean ageCheck = ObjectUtil.isEmpty(user.getIdNumber())?true:bigMan;
        userDto.setAgeCheck(ageCheck);
        return ServerResponseEntity.success(userDto);
    }

    @SneakyThrows
    @PutMapping("/setUserInfo")
    @Operation(summary = "设置用户信息", description = "设置用户信息")
    public ServerResponseEntity<Void> setUserInfo(@RequestBody UserInfoParam userInfoParam) {
        if (StrUtil.isBlank(userInfoParam.getNickName()) && StrUtil.isNotEmpty(userInfoParam.getNickName())) {
            throw new YamiShopBindException("yami.not.null");
        }
        if(StrUtil.isNotEmpty(userInfoParam.getNickName())){
            // 判断是否存在Emoji 表情
            Pattern p = Pattern
                    .compile("[^\\u0000-\\uFFFF]");
            Matcher m = p.matcher(userInfoParam.getNickName());
            if(m.find()){
                throw new YamiShopBindException("yami.user.info.check.expression");
            }
            //个人昵称限制
            List<String> allShopShortNameList = shopDetailService.getAllShopShortNameList();
            String value = sysConfigService.getValue("GROUP_NAME_CHECK");//群敏感词设置
            if(StrUtil.isNotEmpty(value)){
                String[] split = value.split(",");
                allShopShortNameList.addAll(Arrays.asList(split));
            }
            if (CollectionUtil.isNotEmpty(allShopShortNameList)){
                for (String sensitiveUrl : allShopShortNameList) {
                    if (userInfoParam.getNickName().contains(sensitiveUrl)){
                        throw new YamiShopBindException("yami.user.info.check.nickname");
                    }
                }
            }
        }
        String userId = SecurityUtils.getUser().getUserId();
        User user = new User();
        user.setUserId(userId);
        user.setPic(StrUtil.isBlank(userInfoParam.getAvatarUrl()) ? user.getPic() : userInfoParam.getAvatarUrl());
        user.setSex(userInfoParam.getSex() == null ? user.getSex() : userInfoParam.getSex());
        MeltCloudUser meltCloudUser = new MeltCloudUser();
        // 修改融云用户头像
        if (ObjectUtils.isNotEmpty(userInfoParam.getAvatarUrl())) {
            meltCloudUser.setUserPortrait(userInfoParam.getAvatarUrl());
            user.setQrcodeAddr(userService.createUserQrcode(false, userId, userInfoParam.getAvatarUrl()));
        }
        user.setUserMobile(userInfoParam.getUserMobile() == null ? user.getUserMobile() : userInfoParam.getUserMobile());
        user.setBirthDate(userInfoParam.getBirthDate() == null ? user.getBirthDate() : userInfoParam.getBirthDate());
        user.setUserMail(StrUtil.isNotBlank(userInfoParam.getUserMail()) ? userInfoParam.getUserMail() : user.getUserMail());

        if (StrUtil.isNotBlank(userInfoParam.getNickName())) {
            if (sensitiveHandler.isSensitive(userInfoParam.getNickName())) {
                throw new YamiShopBindException("yami.sensitive.words.reenter");
            }
            user.setNickName(userInfoParam.getNickName());
            // 修改融云昵称
            meltCloudUser.setUserName(userInfoParam.getNickName());
        }
        if (StrUtil.isNotBlank(userInfoParam.getAvatarUrl()) || StrUtil.isNotBlank(userInfoParam.getNickName())) {
            meltCloudUser.setId(userId);
            meltCloudUserService.updateById(meltCloudUser);
        }
        // 如果有一项不为空，则发送事件，修改分销员信息（如果是分销员）
        if (StrUtil.isNotBlank(userInfoParam.getAvatarUrl()) || StrUtil.isNotBlank(userInfoParam.getNickName())) {
            applicationContext.publishEvent(new UpdateDistributionUserEvent(userInfoParam, user.getUserId()));
        }
        user.setMoodState(StrUtil.isNotBlank(userInfoParam.getMoodState()) ? userInfoParam.getMoodState() : null);
        userService.updateById(user);
        return ServerResponseEntity.success();
    }


    @PostMapping("/setPayPwd")
    @Operation(summary = "设置交易密码", description = "设置交易密码")
    public ServerResponseEntity<Void> setPayPwd(@Valid @RequestBody PayPasswordParam payPasswordParam) {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getById(userId);
        if (StrUtil.isNotEmpty(user.getPayPassword())) {
            // 修改支付密码
            if (StrUtil.isEmpty(payPasswordParam.getOldPassword())) {
                return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.user.oldpassword.no.exist"));
            }
            String oldDecryptPassword = passwordManager.decryptPassword(payPasswordParam.getOldPassword());
            if (!passwordEncoder.matches(oldDecryptPassword, user.getPayPassword())) {
                return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.user.oldpassword.error"));
            }
        }
        String decryptPassword = passwordManager.decryptPassword(payPasswordParam.getPassword());
        return getVoidServerResponseEntity(user, decryptPassword);
    }

    private ServerResponseEntity<Void> getVoidServerResponseEntity(User user, String decryptPassword) {
        boolean matching = PrincipalUtil.isMatching(PrincipalUtil.PASS_REGEXP, decryptPassword);
        if (!matching) {
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.user.newpassword.check"));
        }
        if (StrUtil.isNotEmpty(user.getPayPassword()) && passwordEncoder.matches(decryptPassword, user.getPayPassword())) {
            throw new YamiShopBindException("yami.user.password.check");
        }
        String encodePayPwd = passwordEncoder.encode(decryptPassword);
        user.setModifyTime(new Date());
        user.setPayPassword(encodePayPwd);
        userService.updateById(user);
        return ServerResponseEntity.success();
    }


    @PutMapping("/checkSetPayPwdSms")
    @Operation(summary = "找回交易密码验证码校验", description = "校验验证码返回校验成功的标识")
    public ServerResponseEntity<String> checkSetPayPwdSms(@RequestBody CheckRegisterSmsParam checkRegisterSmsParam) {
        String userId = SecurityUtils.getUser().getUserId();
        boolean isCheckPass = false;
        if (Objects.nonNull(checkRegisterSmsParam) && Objects.nonNull(checkRegisterSmsParam.getMobile())) {
            Matcher m = Pattern.compile(PrincipalUtil.MOBILE_REGEXP).matcher(checkRegisterSmsParam.getMobile());
            isCheckPass = m.matches();
        }
        if (!isCheckPass) {
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.user.err.phone"));
        }
        User user = userService.getById(userId);
        if (!StrUtil.equals(user.getUserMobile(), checkRegisterSmsParam.getMobile())) {
            // 非本人操作
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.user.account.no.party"));
        }
        if (!smsLogService.checkValidCode(user.getUserMobile(), checkRegisterSmsParam.getValidCode(), SendType.SET_PAY_PASSWORD)) {
            // 验证码有误或已过期
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.user.code.error"));
        }
        String checkRegisterSmsFlag = IdUtil.simpleUUID();
        RedisUtil.set(CHECK_SET_PAY_PWD_SMS_FLAG + checkRegisterSmsFlag, checkRegisterSmsParam.getMobile(), 600);

        return ServerResponseEntity.success(checkRegisterSmsFlag);
    }


    @PutMapping("/resetPayPwd")
    @Operation(summary = "找回交易密码", description = "重置交易密码")
    public ServerResponseEntity<Void> resetPayPwd(@Valid @RequestBody UserPwdUpdateParam userPwdUpdateParam) {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getById(userId);
        if (!StrUtil.equals(user.getUserMobile(), userPwdUpdateParam.getMobile())) {
            // 非本人操作
            throw new YamiShopBindException("yami.user.account.no.party");
        }
        UserRegisterParam registerParam = BeanUtil.map(userPwdUpdateParam, UserRegisterParam.class);
        // 看看有没有校验验证码成功的标识
        ServerResponseEntity<Void> validate = userService.validate(registerParam, CHECK_SET_PAY_PWD_SMS_FLAG + userPwdUpdateParam.getCheckRegisterSmsFlag());
        if(!validate.isSuccess()){
            return ServerResponseEntity.showFailMsg(validate.getMsg());
        }
        String decryptPassword = passwordManager.decryptPassword(userPwdUpdateParam.getPassword());
        if (StrUtil.isBlank(decryptPassword)) {
            // 新密码不能为空
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.user.password.no.exist"));
        }
        return getVoidServerResponseEntity(user, decryptPassword);
    }

    @PostMapping("/checkPayPwd")
    @Operation(summary = "验证交易密码", description = "验证交易密码")
    public ServerResponseEntity<Void> checkPayPwd(@Valid @RequestBody PayPasswordParam payPasswordParam) {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getById(userId);
        if (StrUtil.isEmpty(user.getPayPassword())) {
            return ServerResponseEntity.showFailMsg("请设置交易密码！");
        }
        String decryptPassword = passwordManager.decryptPassword(payPasswordParam.getPassword());
        if (!passwordEncoder.matches(decryptPassword, user.getPayPassword())) {
            return ServerResponseEntity.fail(ResponseEnum.PASSWORD_CHECK_ERROR);
        }
        return ServerResponseEntity.success();
    }

    @PutMapping("/setProdRecommendation")
    @Operation(summary = "设置用户个性化推荐", description = "设置用户个性化推荐")
    public ServerResponseEntity<Void> setProdRecommendation(@RequestBody UserInfoParam userInfoParam) {
        String userId = SecurityUtils.getUser().getUserId();
        User user = new User();
        user.setUserId(userId);
        user.setProdRecommendation(userInfoParam.getProdRecommendation());
        userService.updateById(user);
        return ServerResponseEntity.success();
    }

    @GetMapping("/centerInfo")
    @Operation(summary = "个人中心信息", description = "获取用户个人中心信息")
    public ServerResponseEntity<UserCenterInfoDto> centerInfo() {
        String userId = SecurityUtils.getUser().getUserId();
        UserCenterInfoDto userCenterInfoDto = new UserCenterInfoDto();
        userCenterInfoDto.setOrderCountData(orderService.getOrderCount(userId));
        ShopAuditing shopAuditing = shopAuditingService.getShopAuditingByUserId(userId);
        userCenterInfoDto.setShopAuditStatus(shopAuditing == null ? null : shopAuditing.getStatus());
        ShopDetail shopDetail = shopDetailService.getShopDetailByUserId(userId);
        userCenterInfoDto.setIsSetPassword(shopDetail != null && StrUtil.isNotBlank(shopDetail.getPassword()));
        userCenterInfoDto.setShopId(shopDetail == null ? null : shopDetail.getShopId());
        userCenterInfoDto.setShopStatus(shopDetail == null ? null : shopDetail.getShopStatus());
        return ServerResponseEntity.success(userCenterInfoDto);
    }

    @GetMapping("/getUserScore")
    @Operation(summary = "获取用户积分", description = "返回用户的积分信息")
    public ServerResponseEntity<UserParam> getUserScore() {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getById(userId);
        UserParam userParam = BeanUtil.map(user, UserParam.class);
        System.out.println();
        return ServerResponseEntity.success(userParam);
    }

    @GetMapping("/getUserInfo")
    @Operation(summary = "获取用户信息", description = "返回用户的信息")
    public ServerResponseEntity<UserInfoDto> getUserInfo() {
        String userId = SecurityUtils.getUser().getUserId();
        UserInfoDto userInfo = userExtensionService.getUserInfo(userId);
        return ServerResponseEntity.success(userInfo);
    }

    @Operation(summary = "注销账户", description = "注销账户")
    @GetMapping("/destroy")
    @Parameter(name = "forceDestroy", description = "强制注销")
    public ServerResponseEntity<Void> destroy(@RequestParam(name = "forceDestroy", required = false, defaultValue = "false") Boolean forceDestroy,
                                              @RequestParam("mobile")   String mobile,
                                              @RequestParam("code")     String code) {
        // 验证码登录
        boolean validCode;
        try {
            validCode = smsLogService.checkValidCode(mobile, code, SendType.CANCEL);
        } catch (YamiShopBindException e) {
            // 验证码校验过频繁，请稍后再试
            throw new YamiShopBindException("yami.user.code.check.too.much");
        }
        if (!validCode) {
            // 验证码有误或已过期
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.user.code.error"));
        }
        String userId = SecurityUtils.getUser().getUserId();
        // 检查此账户是否有未完成的订单
        OrderCountData orderCount = orderService.getOrderCount(userId);

        if (orderCount.getConsignment() + orderCount.getPayed() + orderCount.getRefund() + orderCount.getGrouping() > 0) {
            // 存在未完成订单不能注销
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.order.unfinished.cannot.destroy.account"));
        }
        if (!forceDestroy) {
            // 用户余额
            Double balance = 0.00;
            // 分销可提现余额
            Double settledAmount = 0.00;
            // 检查余额
            UserInfoDto userInfo = userExtensionService.getUserInfo(userId);
            if (userInfo.getTotalBalance() > 0) {
                balance = userInfo.getTotalBalance();
            }
            // 检查分销账户余额
            DistributionUser distributionUser = distributionUserService.getByUserIdAndShopId(userId, Constant.PLATFORM_SHOP_ID);
            if (Objects.nonNull(distributionUser)) {
                AchievementDataDto achievementDataDto = distributionUserService.getAchievementDataDtoById(distributionUser.getDistributionUserId());
                DistributionUserWalletDto distributionUserWallet = achievementDataDto.getDistributionUserWallet();
                settledAmount = distributionUserWallet.getSettledAmount();
            }
            String warnMsg = "";
            DecimalFormat df = new DecimalFormat("#0.00");
            String formatBanlance = df.format(balance);
            String formatSettledAmount = df.format(settledAmount);
            if (balance > 0 && settledAmount > 0) {
                if (Objects.equals(I18nMessage.getDbLang(), LanguageEnum.LANGUAGE_ZH_CN.getLang())) {
                    warnMsg = "您的账户当前仍有余额" + formatBanlance + "元及分销余额" + formatSettledAmount + "元，注销账户后所有余额将清零，请考虑清楚后再注销";
                } else {
                    warnMsg = "You still have" + formatBanlance + " dollars and settledAmount " + formatSettledAmount + " dollars in your account, all balance will be cleared after you destroy the account. Please consider carefully before operation";
                }
                return ServerResponseEntity.showFailMsg(warnMsg);
            } else if (balance > 0) {
                if (Objects.equals(I18nMessage.getDbLang(), LanguageEnum.LANGUAGE_ZH_CN.getLang())) {
                    warnMsg = "您的账户当前仍有余额" + formatBanlance + "元，注销账户后所有余额将清零，请考虑清楚后再注销";
                } else {
                    warnMsg = "You still have" + formatBanlance + " dollars in your account, all balance will be cleared after you destroy the account. Please consider carefully before operation";
                }
                return ServerResponseEntity.showFailMsg(warnMsg);
            } else if (settledAmount > 0) {
                if (Objects.equals(I18nMessage.getDbLang(), LanguageEnum.LANGUAGE_ZH_CN.getLang())) {
                    warnMsg = "您的账户当前仍有分销余额" + formatSettledAmount + "元，注销账户后所有余额将清零，请考虑清楚后再注销";
                } else {
                    warnMsg = "You still have settledAmount " + formatSettledAmount + " dollars in your account, all balance will be cleared after you destroy the account. Please consider carefully before operation";
                }
                return ServerResponseEntity.showFailMsg(warnMsg);
            }
        }
        userService.destroyUser(userId);
        return ServerResponseEntity.success();
    }

    /**
     * 新生钱包个人开户
     *
     * @param personalAccountOpenParam personalAccountOpenParam
     * @return
     */
    @PostMapping("/personalAccountOpening")
    @Operation(summary = "新生钱包个人开户", description = "新生钱包个人开户")
    public ServerResponseEntity<Void> personalAccountOpening(@Valid @RequestBody PersonalAccountOpenParam personalAccountOpenParam) {
        YamiUser user = SecurityUtils.getUser();
        if (!user.getEnabled()) {
            throw new YamiShopBindException("yami.order.pay.user.disable");
        }
        //判断身份证 唯一
        User param = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getIdNumber, personalAccountOpenParam.getCertNo()).eq(User::getStatus, 1));
        if(ObjectUtil.isNotEmpty(param)){
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.dtc.user.check.idnumber"));
        }

        String redisKey = UserCacheNames.USER + "opening:" + user.getUserId();
        int number = 1;
        if (RedisUtil.hasKey(redisKey)) {
            number = RedisUtil.get(redisKey);
            if (number <= 3) {
                RedisUtil.set(redisKey, number++, 86400);
                return openPersonalAccount(personalAccountOpenParam);
            }
        } else {
            RedisUtil.set(redisKey, number, 86400);
            return openPersonalAccount(personalAccountOpenParam);
        }
        return ServerResponseEntity.showFailMsg("开户失败");
    }

    private ServerResponseEntity<Void> openPersonalAccount(PersonalAccountOpenParam personalAccountOpenParam) {
        try {
            Map<String, Object> responseMap = userService.personalAccountOpening(personalAccountOpenParam);
            if (responseMap.get("resultCode").toString().equals("0000")) {
                return ServerResponseEntity.success();
            } else {
                return ServerResponseEntity.showFailMsg(responseMap.get("errorMsg").toString());
            }
        } catch (RuntimeException r) {
            if (r.getMessage().contains("运营商认证失败")) {
                return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.dtc.user.check.phone"));
            } else {
                return ServerResponseEntity.showFailMsg(r.getMessage());
            }
        }
    }

    /**
     * 新生用户查询
     *
     * @return
     */
    @GetMapping("/personalAccountQuery")
    @Operation(summary = "新生用户查询", description = "新生用户查询")
    public ServerResponseEntity<Map<String, Object>> personalAccountQuery() {
        String xsUserId = SecurityUtils.getUser().getXsUserId();
        Map<String, Object> responseMap = userService.personalAccountQuery(xsUserId);
        if (responseMap.get("resultCode").toString().equals("0000")) {
            return ServerResponseEntity.success(responseMap);
        }
        return ServerResponseEntity.showFailMsg(responseMap.get("errorMsg").toString());
    }

    /**
     * 新生用户查询
     *
     * @return
     */
    @GetMapping("/personalAccountDetailQuery")
    @Operation(summary = "新生用户账户明细查询", description = "新生用户账户明细查询")
    public ServerResponseEntity<Map<String, Object>> personalAccountDetailQuery(XsQueryParam xsQueryParam) {
        String xsUserId = SecurityUtils.getUser().getXsUserId();
        xsQueryParam.setXsUserId(xsUserId);
        Map<String, Object> responseMap = userService.personalAccountDetailQuery(xsQueryParam);
        if (responseMap.get("resultCode").toString().equals("0000")) {
            return ServerResponseEntity.success(responseMap);
        }
        return ServerResponseEntity.showFailMsg(responseMap.get("errorMsg").toString());
    }


    @GetMapping("/removeHwjInfo")
    @Operation(summary = "解绑海文交账号", description = "解绑海文交账号")
    public ServerResponseEntity removeHwjInfo() {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getUserByUserId(userId);
        if (Objects.isNull(user.getSettleAccount())) {
            return ServerResponseEntity.showFailMsg("该用户没有绑定");
        }
        userService.removeHwjInfo(userId);
        return ServerResponseEntity.success();
    }

    @GetMapping("/getUserWithdrawCashConfig")
    @Operation(summary = "获取用户信息", description = "返回用户的信息")
    public ServerResponseEntity<UserBalanceWithdrawCashConfigVO> getUserWithdrawCashConfig() {
        return ServerResponseEntity.success(userBalanceWithdrawCashService.getConfig());
    }
}
